/**
 * Map Service
 * 地图控制服务，添加图层、添加几何体和视图，操作地图
 */

angular.module('NxtMap')
  .service('MapService', ['ColorService', MapService]);

function MapService(ColorService) {

  //矢量图
  var layer_vec = new Cesium.WebMapTileServiceImageryProvider({    
    url: "http://{s}.tianditu.com/vec_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",        
    layer: "vec",
    style: "default",
    format: "tiles",
    tileMatrixSetID: "c",
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    tilingScheme : new Cesium.GeographicTilingScheme(),
    tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  });
  //矢量图中文注释
  var layer_cva = new Cesium.WebMapTileServiceImageryProvider({    
    url: "http://{s}.tianditu.com/cva_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg",    
    layer: "cva",        
    style: "default",        
    format: "tiles",        
    tileMatrixSetID: "c",
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    tilingScheme : new Cesium.GeographicTilingScheme(),
    tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  });
  //卫星图
  var layer_img = new Cesium.WebMapTileServiceImageryProvider({    
    url: "http://{s}.tianditu.com/img_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles",        
    layer: "img",        
    style: "default",        
    format: "tiles",        
    tileMatrixSetID: "c",
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    tilingScheme : new Cesium.GeographicTilingScheme(),
    tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  });
  //卫星图中文注释
  var layer_cia = new Cesium.WebMapTileServiceImageryProvider({    
    url: "http://{s}.tianditu.com/cva_c/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=c&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg",    
    layer: "cia",        
    style: "default",        
    format: "tiles",        
    tileMatrixSetID: "c",
    subdomains: ['t0', 't1', 't2', 't3', 't4', 't5', 't6', 't7'],
    maximumLevel: 18,
    tilingScheme : new Cesium.GeographicTilingScheme(),
    tileMatrixLabels: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18']
  });

  var localImg = new Cesium.WebMapServiceImageryProvider({
    url : ' http://10.0.13.216:6080/arcgis/services/haining/ImageServer/WMSServer',
    layers : '0',
    maximumLevel: 18,
    // proxy: new Cesium.DefaultProxy('/proxy/')
  });
  var localAnnotation = new Cesium.WebMapServiceImageryProvider({
    url : ' http://10.0.13.216:6080/arcgis/services/haining/ImageServer/WMSServer',
    layers : '0',
    maximumLevel: 18,
    // proxy: new Cesium.DefaultProxy('/proxy/')
  });

  //地图viewer，MapService统一控制，全局唯一
  Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(120.40001, 30.25014, 120.70001, 30.61014);
  Cesium.Camera.DEFAULT_VIEW_FACTOR = 0;
  var viewer = new Cesium.Viewer("cesiumContainer", {
    animation: false,  //是否显示动画控件    
    baseLayerPicker: false, //是否显示图层选择控件    
    geocoder: false, //是否显示地名查找控件    
    timeline: false, //是否显示时间线控件    
    sceneModePicker: true, //是否显示投影方式控件    
    navigationHelpButton: false, //是否显示帮助信息控件    
    infoBox: false,  //是否显示点击要素之后显示的信息    
    scene3DOnly: false,
    // sceneMode : Cesium.SceneMode.SCENE2D, //使用2D地图模式
    fullscreenButton: false,
    imageryProvider : layer_vec
  });
  viewer.imageryLayers.addImageryProvider(layer_cva); 
  // viewer.imageryLayers.addImageryProvider(localImg);
  // viewer.imageryLayers.addImageryProvider(localAnnotation);
  viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
  this.viewer = viewer;
  this.handler = viewer.cesiumWidget.screenSpaceEventHandler;
  //热力图模型heatmap
  var area = {
    north: 31.63277, 
    east: 121.7821, 
    south: 29.43277, 
    west: 119.5821
  };
  var heatmap = CesiumHeatmap.create(viewer, area, {radius: 5,});
  
  //改变地图类型， 0为矢量图， 1为卫星图
  this.changeMap = function (mapType, value) {
    if(mapType != value){
      viewer.imageryLayers.removeAll();
      if(value == 0) {
        viewer.imageryLayers.addImageryProvider(layer_vec);
        viewer.imageryLayers.addImageryProvider(layer_cva);
      }
      else {
        viewer.imageryLayers.addImageryProvider(layer_img);
        viewer.imageryLayers.addImageryProvider(layer_cia);
      }
    }
    return value;
  }
  //初始化地图
  this.initMap = function () {
    Cesium.Camera.DEFAULT_VIEW_RECTANGLE = Cesium.Rectangle.fromDegrees(120.45001, 30.33014, 120.65001, 30.53014);
    Cesium.Camera.DEFAULT_VIEW_FACTOR = 0;
    var viewer = new Cesium.Viewer("cesiumContainer", {
      animation: false,  //是否显示动画控件    
      baseLayerPicker: false, //是否显示图层选择控件    
      geocoder: false, //是否显示地名查找控件    
      timeline: false, //是否显示时间线控件    
      sceneModePicker: true, //是否显示投影方式控件    
      navigationHelpButton: false, //是否显示帮助信息控件    
      infoBox: false,  //是否显示点击要素之后显示的信息    
      scene3DOnly: false,
      // sceneMode : Cesium.SceneMode.SCENE2D, //使用2D地图模式
      fullscreenButton: false,
      imageryProvider : layer_vec
    });
    viewer.imageryLayers.addImageryProvider(layer_cva);
    return viewer;
  }
  //根据给出的经纬度和旋转角度，调整视角到该处
  this.setPosition = function(lng, lat, offset, rotateAngle) {
    var positionEntity = viewer.entities.add({
      polygon : {
        hierarchy : Cesium.Cartesian3.fromDegreesArray([
          lng - offset, lat + offset,
          lng + offset, lat + offset,
          lng + offset, lat - offset,
          lng - offset, lat - offset
        ]), 
        material : new Cesium.Color(0, 0, 0, 0),
        outline : false
      }
    });
    viewer.zoomTo(positionEntity, new Cesium.HeadingPitchRange(0, rotateAngle, 0));
  }

  this.flyHome = function () {
    viewer.camera.flyHome(2);
  }

  //根据类型type，返回需要的图形
  this.drawMap = function(type, originData, data, param) {
    this.clearMap();
    switch(type) {
      case 'square':
        return this.drawSquare(data, param);
      case 'hexagon':
        return this.drawHexagon(data, param);
      case 'heatmap':
        return this.drawHeatmap(originData);
      case 'station':
        return this.drawStationBorder(data, param);
      case 'cross':
        return this.drawRoad();
    }
  }

  this.clearMap = function() {
    pointPrimitives.removeAll();
    viewer.entities.removeAll();
    this.removeHeatmap();
  }
  
  // 添加方格密度柱状图
  this.drawSquare = function (data, param) {
    var result = [];
    result.objects = [];
    result.sum = 0;
    for(var i = 0; i < data.dataS.length * param.lenPercent; i++){
      var point = data.dataS[i];
      result.push(point);
      result.sum += point.value;
      result.objects = result.objects.concat(point.objects);
      if(param.timeline){
        if(point.timeline != param.timeline){
          continue;
        }
      }
      var lng = data.minlng + point.lngNo * data.s;
      var lat = data.minlat + point.latNo * data.s;
      var value = point.value;
      var color = ColorService.getColorGR(Math.sqrt(value - 1), Math.sqrt(data.maxS) / 2.2);

      var wyoming = viewer.entities.add({
        name: i,
        polygon : {
          hierarchy : Cesium.Cartesian3.fromDegreesArray([
            lng, lat,
            lng + data.s, lat,
            lng + data.s, lat + data.s,
            lng, lat + data.s
          ]), 
          material : new Cesium.Color(color[0], color[1], color[2], param.opacity),
          outline : false,
          outlineColor : new Cesium.Color(0.8, 0.8, 0.8, 1),
          extrudedHeight: Math.sqrt(value) * param.heightBase
        }
      });
    }

    return result;
  };

  // 添加方格几何体（只用于显示效果，没有其他操作）
  this.drawSquareGeometry = function (data, param) {
    var instances = [];
    for(var i = 0; i < data.dataS.length * param.lenPercent; i++){
      var point = data.dataS[i];
      if(param.timeline){
        if(point.timeline != param.timeline){
          continue;
        }
      }
      var lng = data.minlng + point.lngNo * data.s;
      var lat = data.minlat + point.latNo * data.s;
      var value = point.value;
      var color = ColorService.getColorGR(Math.sqrt(value - 1), Math.sqrt(data.maxS) / 2.2);

      instances.push(new Cesium.GeometryInstance({
        geometry : new Cesium.RectangleGeometry({
          rectangle : Cesium.Rectangle.fromDegrees(lng, lat, lng + data.s, lat + data.s)
        }),
        attributes : {
          color : Cesium.ColorGeometryInstanceAttribute.fromColor(
            new Cesium.Color(color[0], color[1], color[2], param.opacity))
        }
      }));
    }
    viewer.scene.primitives.add(new Cesium.Primitive({
      geometryInstances : instances,
      appearance : new Cesium.PerInstanceColorAppearance({
        flat : true,
        translucent : true
      })
    }));
    return data.dataS;
  };

  // 添加蜂窝密度柱状图
  this.drawHexagon = function (data, param) {
    var r = data.r;
    var h = data.h;
    var s = data.s;

    for(var i = 0; i < data.dataH.length * param.lenPercent; i++){
      var point = data.dataH[i];
      if(param.timeline){
        if(point.timeline != param.timeline){
          continue;
        }
      }
      var clng = data.minClng + point.lngNo * r * 2 + (point.latNo % 2) * r;
      var clat = data.minClat + point.latNo * (h + s);
      var value = point.value;
      var color = ColorService.getColorGR(Math.sqrt(value - 1), Math.sqrt(data.maxH) / 2.2);

      var wyoming = viewer.entities.add({
        name: i,
        polygon : {
          hierarchy : Cesium.Cartesian3.fromDegreesArray([
            clng - r, clat + h,
            clng, clat + s,
            clng + r, clat + h,
            clng + r, clat - h,
            clng, clat - s,
            clng - r, clat - h
          ]), 
          material : new Cesium.Color(color[0], color[1], color[2], param.opacity),
          outline : false,
          // outlineColor : new Cesium.Color(red, green, 0, 1),
          extrudedHeight: Math.sqrt(value) * param.heightBase
        }
      });
    }
    return data.dataH;
  }


  //描绘轨迹点图，配合label
  this.drawTrackPoint = function (data) {
    for(var i = 0; i < data.length; i++){
      var point = data[i];
      var lng = data[i].lng;
      var lat = data[i].lat;
      //point
      var wyoming = viewer.entities.add({
        id: data[i].id,
        name: data[i].card_id,
        position: Cesium.Cartesian3.fromDegrees(lng, lat, 10),
        billboard: {
          width : 30,
          height: 40,
          image: 'img/important.png',
          pixelOffset : new Cesium.Cartesian2(0.0, -16),
          pixelOffsetScaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.3),
          scaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.3)
        }
      });
      //label
      var text = '时间：' + (new Date(data[i].upload_time)).format('yyyy-MM-dd HH:mm') 
        + '\n地点：' + data[i].device_id;
      var label = viewer.entities.add({
        id: data[i].id + '-label',
        position: Cesium.Cartesian3.fromDegrees(lng, lat, 10),
        label: {
          show: false,
          text : text,
          font : '20px Microsoft Yahei',
          fillColor : Cesium.Color.BLACK,
          outlineColor : Cesium.Color.SKYBLUE,
          outlineWidth : 2,
          style : Cesium.LabelStyle.FILL,
          pixelOffset : new Cesium.Cartesian2(0.0, -36),
          pixelOffsetScaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.3),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          scaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.1),
          showBackground: true,
          backgroundColor: Cesium.Color.WHITE,
          backgroundPadding: new Cesium.Cartesian2(5, 5),
        }
      });

    }
    return data.dataS;
  }


  //描绘点图，几何体
  var pointPrimitives = new Cesium.PrimitiveCollection();
  viewer.scene.primitives.add(pointPrimitives);
  this.drawPointGeometry = function (data) {
    var instances = [];
    for(var i = 0; i < data.length; i++){
      if(i > 10000){
        break;
      }
      var point = data[i];
      var lng = data[i].JD;
      var lat = data[i].WD;
      
      instances.push(new Cesium.GeometryInstance({
        geometry : new Cesium.CircleGeometry({
          center : Cesium.Cartesian3.fromDegrees(lng, lat),
          radius : 20.0,
          height : 20
        }),
        attributes : {
          color : Cesium.ColorGeometryInstanceAttribute.fromColor(Cesium.Color.RED)
        }
      }));

    }
    pointPrimitives.add(new Cesium.Primitive({
      geometryInstances : instances,
      appearance : new Cesium.PerInstanceColorAppearance({
        flat : true,
        translucent : false
      })
      // appearance : new Cesium.MaterialAppearance({
      //   material: new Cesium.Material({
      //     fabric : {
      //       type : 'Image',
      //       uniforms : {
      //         image : 'img/default.png'
      //       }
      //     }
      //   }),
      //   faceForward: true
      // })
    }));
  }

  var len = 0;
  //描绘热力图
  this.drawHeatmap = function (data) {
    var len = data.length;
    var result = [];
    result.objects = data;
    result.sum = data.length;
    var hData = [];
    for(var i = 0; i < data.length; i++){
      var point = data[i];
      var lng = data[i].JD;
      var lat = data[i].WD;
      hData.push({x: lng, y: lat, value: 1});
    }
    var rate = getRate(len);
    heatmap = CesiumHeatmap.create(viewer, area, {radius: rate[0]});
    heatmap.setWGS84Data(0, rate[1], hData);
    // 添加实体的点击操作
    // var scene = viewer.scene;
    // viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
    // handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
    viewer.cesiumWidget.screenSpaceEventHandler.setInputAction(function(movement) {
      var rate = getRate(len);
      console.log(rate);
      heatmap._cesium.scene.imageryLayers.remove(heatmap._layer);
      heatmap = CesiumHeatmap.create(viewer, area, {radius: rate[0]});
      heatmap.setWGS84Data(0, rate[1], hData);
    }, Cesium.ScreenSpaceEventType.WHEEL);
    return result;
  }

  //热力图根据zoom程度变换显示效果参数
  function getRate(len) {
    var cameraPosition = viewer.scene.camera.positionWC;
    var ellipsoidPosition = viewer.scene.globe.ellipsoid.scaleToGeodeticSurface(cameraPosition);
    var distance = Cesium.Cartesian3.magnitude(Cesium.Cartesian3.subtract(cameraPosition, ellipsoidPosition, new Cesium.Cartesian3()));
    var max = Math.sqrt(distance) * len / 100000;
    var radius = Math.sqrt(distance) / 200 + 1.4;
    if(distance > 20000) {
      max = max * 2;
      radius = radius * 2;
    }
    if(distance > 60000) {
      max = max * 2;
      radius = radius * 2;
    }
    return [radius, max];
  }

  //移除热力图
  this.removeHeatmap = function () {
    if(heatmap._layer){
      heatmap._cesium.scene.imageryLayers.remove(heatmap._layer);
    }
    viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(Cesium.ScreenSpaceEventType.WHEEL);
  }

  //rfid轨迹图
  this.drawTrack = function (data) {
    var lineArray = [];
    for(var i = 0; i < data.length - 1; i ++) {
      var img = 'img/point.png';
      var size = 20;
      if(i == 0) {
        img = 'img/start.png';
        size = 30;
      }
      lineArray.push(data[i].lng);
      lineArray.push(data[i].lat);
      lineArray.push(0);
      var point = viewer.entities.add({
        id: data[i].id,
        position: Cesium.Cartesian3.fromDegrees(data[i].lng, data[i].lat, 10),
        billboard: {
          width : size,
          height: size,
          image: img,
          scaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.3)
        }
      });
      // label
      var text = '时间：' + (new Date(data[i].upload_time)).format('yyyy-MM-dd HH:mm') 
        + '\n地点：' + data[i].device_id;
      var label = viewer.entities.add({
        id: data[i].id + '-label',
        position: Cesium.Cartesian3.fromDegrees(data[i].lng, data[i].lat, 10),
        label: {
          show: false,
          text : text,
          font : '20px Microsoft Yahei',
          fillColor : Cesium.Color.BLACK,
          outlineColor : Cesium.Color.SKYBLUE,
          outlineWidth : 2,
          style : Cesium.LabelStyle.FILL,
          pixelOffset : new Cesium.Cartesian2(0.0, -20),
          pixelOffsetScaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.3),
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
          scaleByDistance : new Cesium.NearFarScalar(15, 1.0, 1.5e6, 0.1),
          showBackground: true,
          backgroundColor: Cesium.Color.WHITE,
          backgroundPadding: new Cesium.Cartesian2(5, 5),
        }
      });
    }
    lineArray.push(data[i].lng);
    lineArray.push(data[i].lat);
    lineArray.push(0);
    var pointLine = viewer.entities.add({
      polyline : {
        positions : Cesium.Cartesian3.fromDegreesArrayHeights(lineArray),
        width : 4,
        material : Cesium.Color.fromCssColorString('#006BFF')
      }
    });
  }

  //获取派出所边界
  var points = [];
  $.getJSON('../data/paichusuo.json', function (resp){
     points = resp.geometries;
  });

  //海宁派出所边界图,
  this.drawStationBorder = function (data, param) {
    var result = [];
    result.objects = [];
    result.sum = 0;
    for(var i = 0; i < points.length; i++){
      var array = [];
      for(var j = 0; j < points[i].coordinates[0].length; j++){
        array.push(points[i].coordinates[0][j][0]);
        array.push(points[i].coordinates[0][j][1]);
      }
      
      var value = data.dataStation[i].value;
      if(param.timeline) {
        console.log(data.dataStation[i][param.timeline]);
        if(data.dataStation[i][param.timeline]){
          value = data.dataStation[i][param.timeline].value;
        }
        else {
          value = 0;
        }
      }
      if(value == 0){
        continue;
      }
      result.push(data.dataStation[i]);
      result.objects = result.objects.concat(data.dataStation[i].objects);
      result.sum += data.dataStation[i].value;

      var color = ColorService.getColorGR(Math.sqrt(value), Math.sqrt(data.maxStation) / 1.8);
      var entity = viewer.entities.add({
        name: i,
        polygon : {
          hierarchy : Cesium.Cartesian3.fromDegreesArray(array),
          material : new Cesium.Color(color[0], color[1], color[2], param.opacity),
          outline: true,
          outlineColor : Cesium.Color.GRAY,
          extrudedHeight: Math.sqrt(value) * param.heightBase           
        }
      });
    
    }
    return result;
  }

  var roads = [];
  $.getJSON('../data/street.json', function (resp){
     roads = resp.geometries;
  });
  
  this.drawRoad = function (data) {
    // viewer.dataSources.add(Cesium.GeoJsonDataSource.load('../data/street.json', {
    //   stroke: Cesium.Color.fromCssColorString('#438EFF'),
    //   fill: Cesium.Color.fromCssColorString('#438EFF'),
    //   strokeWidth: 2,
    // }));
    var cont = [];
    for(var i = 0; i < data.road_data.length; i++){
      var road = data.road_data[i];
      var value = road.value;
      var index = road.index; 
      var color = ColorService.getColorGR(Math.sqrt(value - 1), Math.sqrt(data.road_max) / 2.2);

      var array = [];
      for(var j = 0; j < roads[index].coordinates.length; j++){
        array.push(roads[index].coordinates[j][0]);
        array.push(roads[index].coordinates[j][1]);
      }
      cont.push(index);

      var entity = viewer.entities.add({
        name: i,
        polyline : {
          positions: Cesium.Cartesian3.fromDegreesArray(array),
          width: 3,
          material : new Cesium.Color(color[0], color[1], color[2], 1),
        }
      });
    }
    
    for(var i = 0; i < roads.length; i ++) {
      var array = [];
      if(cont.indexOf(i + '') < 0) {
        for(var j = 0; j < roads[i].coordinates.length; j++){
          array.push(roads[i].coordinates[j][0]);
          array.push(roads[i].coordinates[j][1]);
        }
        var entity = viewer.entities.add({
          polyline : {
            positions: Cesium.Cartesian3.fromDegreesArray(array),
            width: 3,
            material : new Cesium.Color(0, 0.64, 0.3, 1),
          }
        });
      }

    }
    return data.road_data;
  }

  this.drawCross = function (data) {
    var percent = 1;
    if(data.max > 25) {
      percent = 25 / data.max;
    }
    for(var i = 0; i < data.data.length; i++){
      var point = data.data[i];
      
      if(!point.position){
        continue;
      }
      var lng = point.position[0];
      var lat = point.position[1];
      var value = point.value;
      var color = ColorService.getColorGR(Math.sqrt(value - 1), Math.sqrt(data.max) / 2.2);

      var entity = viewer.entities.add({
        name: "c-" + i,
        position: Cesium.Cartesian3.fromDegrees(lng, lat),
        ellipse : {
          semiMinorAxis : 40.0,
          semiMajorAxis : 40.0,
          material : new Cesium.Color(color[0], color[1], color[2], 1),
          outline : false,
          outlineColor : new Cesium.Color(0.8, 0.8, 0.8, 1),
          extrudedHeight: value * 20 * percent
        }
      });
    }

    return data.data;
  }

  var rfidPrimitives = new Cesium.PrimitiveCollection();
  viewer.scene.primitives.add(rfidPrimitives);
  this.clearRfidPonit = function (){
    rfidPrimitives.removeAll();
  }

  this.drawCrossTest = function (){
    var instances = [];
    $.getJSON('data/data.json', function (data){
      var points = data.data;
      instances = [];
      for(var i = 0; i < points.length; i++){
        var lng = points[i].lng;
        var lat = points[i].lat;

        // var entity = viewer.entities.add({
        //   name: points[i].address,
        //   position: Cesium.Cartesian3.fromDegrees(lng, lat),
        //   ellipse : {
        //     semiMinorAxis : 80.0,
        //     semiMajorAxis : 80.0,
        //     material : Cesium.Color.fromCssColorString('#176685').withAlpha(1),
        //     outline : false,
        //     outlineColor : new Cesium.Color(0.8, 0.8, 0.8, 1),
        //     extrudedHeight: 1000 * Math.random()
        //   }
        // });

        instances.push(new Cesium.GeometryInstance({
          geometry : new Cesium.CircleGeometry({
            center : Cesium.Cartesian3.fromDegrees(lng, lat),
            radius : 80.0
          }),
          attributes : {
            color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(0.8, 0, 0.2, 0.1))
          }
        }));

      }
      rfidPrimitives.add(new Cesium.Primitive({
        geometryInstances : instances,
        appearance : new Cesium.PerInstanceColorAppearance({
          flat : true,
          translucent : false
        })
      }));

    });
  }


  //道路热力围城
  this.drawHeatRoundCity = function (){
    var string = '';
    $.ajax({
       type: "GET",//请求方式
       url: "../data/quzhoustreet.txt",//地址
       data: "text",
       success: function(msg){//返回的参数就是 action里面所有的有get和set方法的参数
          string = msg;
          draw();
       }
    }); 

    function draw() {
      var instances = [];
      var ss = string.split('\n');
      
      $.getJSON('../data/quzhou.json', function (data){
        var points = data.geometries;
        for(var i = 0; i < 100; i++){
          var array = [];
          for(var j = 0; j < points[i].coordinates.length; j++){
            array.push(points[i].coordinates[j][0]);
            array.push(points[i].coordinates[j][1]);
          }

          
          var cells = ss[i + 1].split(',');
          for(var j = 3; j < 27; j ++){
            var num = cells[j];
            var color = ColorService.getColorBR(Math.sqrt(num), 5);
            var wall = Cesium.WallGeometry.fromConstantHeights({
              positions : Cesium.Cartesian3.fromDegreesArray(array),
              minimumHeight : 10 * (j - 3),
              maximumHeight : 10 * (j - 2)
            });
            var geometry = Cesium.WallGeometry.createGeometry(wall);
            instances.push(new Cesium.GeometryInstance({
              geometry : geometry,
              attributes : {
                color : Cesium.ColorGeometryInstanceAttribute.fromColor(new Cesium.Color(color[0] * 0.8, color[1] * 0.8, color[2] * 0.8, 1))
              }
            }));
          }

          viewer.scene.primitives.add(new Cesium.Primitive({
            geometryInstances : instances,
            appearance : new Cesium.PerInstanceColorAppearance({
              flat : true,
              translucent : false
            })
          }));
        }
      });
    }
  }

}